package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.OrderPaymentManager;
import com.inter.entity.interentity.queryresults.request.RequestQueryPaymentResults;
import com.inter.entity.interentity.queryresults.request.RequestQueryPaymentResultsData;
import com.inter.entity.interentity.queryresults.request.RequestQueryPaymentResultsTradeData;
import com.inter.entity.interentity.queryresults.response.ResponseQueryPaymentResults;
import com.inter.entity.interentity.queryresults.response.ResponseQueryPaymentResultsData;
import com.inter.entity.interentity.queryresults.response.ResponseQueryPaymentResultsTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.service.OrderPaymentManagerService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@Api(description = "查询支付结果")
public class QueryPaymentResultsController {

    private static Logger logger = Logger.getLogger(QueryPaymentResultsController.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    OrderPaymentManagerService orderPaymentManagerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    /****
     *
     * @param requestQueryPaymentResults
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "queryPaymentResults", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "支付结果查询", response = ResponseQueryPaymentResults.class)
    public String resultsQuery(@ApiParam @RequestBody RequestQueryPaymentResults requestQueryPaymentResults) throws Exception {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString = "";
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestQueryPaymentResults);

        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestQueryPaymentResults requestPackage = JSONArray.parseObject(requestStr, RequestQueryPaymentResults.class);
            String requestSign = requestPackage.getSign();
            if (requestSign == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestQueryPaymentResultsData requestData = requestPackage.getData();
                if (requestData == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    RequestQueryPaymentResultsTradeData requestTradeData = requestData.getTradeData();
                    if (requestTradeData == null || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang)) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String orderId = requestTradeData.getOrderId();
                        String deviceId = requestTradeData.getDeviceId();
                        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(deviceId)) {
                            logger.info("请求报文不合法:orderId和deviceId不可以为空！");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //现在开始准备回传的数据：
                                List<OrderPaymentManager> orderList = orderPaymentManagerService.getOrderResultsList(orderId, deviceId);
                                if (orderList == null || orderList.isEmpty()) {
                                    ResponseQueryPaymentResultsData data = new ResponseQueryPaymentResultsData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(1201);
                                    data.setTradeRstMessage("未查询到当前订单支付记录");

                                    ResponseQueryPaymentResults results = new ResponseQueryPaymentResults();
                                    results.setData(data);
                                    results.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(results);
                                    logger.info("响应报文：" + jsonString);
                                    return jsonString;

                                } else {
                                    for (OrderPaymentManager userOrder : orderList) {

                                        String packageName = userOrder.getPackageName();
                                        String packageNameEN = partnerProductPackageService.queryPackageName(packageName, partnerCode);
                                        String orderCode = userOrder.getOrderId();
                                        String deviceCode = userOrder.getDeviceId();
                                        String deviceType = userOrder.getDeviceType();
                                        String payType = userOrder.getPayType();
                                        String payAmount = userOrder.getAmount();
                                        String payRst = userOrder.getPayRst();
                                        String orderCurrency = userOrder.getOrderCurrency();
                                        //判断一下支付结果是不是success
                                        if (payRst != null && payRst != "" && payRst.equals("success")) {
                                            ResponseQueryPaymentResultsTradeData responseTradeData = new ResponseQueryPaymentResultsTradeData();
                                            if ("en".equals(lang)) {
                                                responseTradeData.setPackageName(packageNameEN);
                                            } else {
                                                responseTradeData.setPackageName(packageName);
                                            }
                                            responseTradeData.setOrderId(orderCode);
                                            responseTradeData.setDeviceId(deviceCode);
                                            responseTradeData.setDeviceType(deviceType);
                                            responseTradeData.setPayType(payType);
                                            responseTradeData.setPayAmount(payAmount);
                                            responseTradeData.setPayRst(payRst);
                                            responseTradeData.setOrderCurrency(orderCurrency);

                                            ResponseQueryPaymentResultsData data = new ResponseQueryPaymentResultsData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setToken(token);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(curtime);
                                            data.setTradeRstCode(1000);
                                            data.setTradeRstMessage("success");
                                            data.setTradeData(responseTradeData);

                                            ResponseQueryPaymentResults results = new ResponseQueryPaymentResults();
                                            results.setData(data);
                                            results.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(results);
                                            logger.info("响应报文：" + jsonString);
                                            return jsonString;

                                        } else {//走这里说明至少订单没有支付成功payRst！=success
                                            ResponseQueryPaymentResultsData data = new ResponseQueryPaymentResultsData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setToken(token);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(curtime);
                                            data.setTradeRstCode(1202);
                                            data.setTradeRstMessage("The current order was not successfully paid！当前订单未成功支付！");

                                            ResponseQueryPaymentResults results = new ResponseQueryPaymentResults();
                                            results.setData(data);
                                            results.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(results);
                                            logger.info("响应报文：" + jsonString);
                                            return jsonString;

                                        }


                                    }


                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
}


